<template>
  <div class="salon_region_select" :class="display == 'col' ? 'srcol' : isAdmin ? 'srrow' : 'ssalon'">
    <div v-if="isAdmin" class="resion_select">
      <el-radio-group v-model="depth" size="small" @input="handleDepthChange">
        <el-radio-button :label="2">市级</el-radio-button>
        <el-radio-button :label="3">区级</el-radio-button>
      </el-radio-group>
      <el-cascader
        ref="refCascader"
        :key="keyForCascader"
        v-model="selectedOptions"
        :options="areaSelectData"
        :props="{ multiple: multiple }"
        :show-all-levels="true"
        clearable
        filterable
        size="small"
        placeholder="可搜索, 如: 成都"
        :style="{ width: display == 'col' ? '243px' : 'auto' }"
        @change="handleRegionChange"></el-cascader>
    </div>
    <div v-if="mode == 2">
      <i v-if="isSalonLoading" class="el-icon-loading"></i>
      <el-select
        v-else
        v-model="salon.salonId"
        placeholder="-请选择-, 可搜索, 如: 逆时光"
        :disabled="isSalonLoading || isDisabled"
        clearable
        filterable
        size="small"
        style="width: 330px"
        @change="handleSalonChange">
        <el-option v-for="item in salonList" :key="item.id" :label="item.sname" :value="item.id"></el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
// 引入后端 API
import { getSalonByRegion, getSalonInRegion } from '@/api/salon';
// 引入自定义组件
import '@/utils/datefmt';
import { isAdminRole } from '@/utils/enum/roles';
// 引入第三方组件
import { codeToText, provinceAndCityData, regionData } from 'element-china-area-data';
import { MessageBox } from 'element-ui';
import pinyin from 'js-pinyin';
import { mapGetters } from 'vuex';

// ['51', '5101', '510107'] 默认显示：四川省成都市武侯区

export default {
  name: '',
  props: {
    mode /* 1-只选区划; 2-根据区划筛选门店 */: {
      type: Number,
      required: false,
      default: 1,
    },
    dept: {
      type: Number,
      required: false,
      default: 3,
    },
    multiple: {
      type: Boolean,
      required: false,
      default: false,
    },
    display: {
      type: String,
      required: false,
      default: 'col',
    },
  },
  data() {
    return {
      keyForCascader: 1,
      areaSelectData: undefined,
      selectedOptions: [], // 默认显示：四川省成都市武侯区
      depth: this.dept,
      location: undefined,
      salonCode: undefined,
      regionCode: undefined,
      salonList: [],
      salon: {
        salonId: undefined,
        salonCode: '',
        salonName: '',
      },
      isSalonLoading: false,
      isDisabled: false,
    };
  },
  computed: {
    ...mapGetters(['deptId', 'openId', 'id', 'name']),
    isAdmin() {
      return isAdminRole(this.deptId);
    },
  },
  created() {
    if (!this.isAdmin) {
      this.loadShowSalons();
    }
    this.handleDepthChange();
  },
  methods: {
    handleDepthChange() {
      if (this.depth == 2) {
        this.areaSelectData = provinceAndCityData;
      } else if (this.depth == 3) {
        this.areaSelectData = regionData;
      }
    },
    handleRegionChange(val) {
      this.initRegionPath(val);
      this.loadShowSalons();
      const cpyRegionPath = [];
      cpyRegionPath.push(...this.selectedOptions);
      this.$emit('change', {
        regionCode: this.regionCode,
        salonCode: this.salonCode,
        location: this.location,
        regionPath: cpyRegionPath,
      });
    },
    initRegionPath(val) {
      if (val.length) {
        this.regionCode = val[val.length - 1];
      }

      this.location = codeToText[this.selectedOptions[0]];
      this.location += codeToText[this.selectedOptions[1]];
      if (this.selectedOptions.length > 2 && this.selectedOptions[2]) {
        this.location += codeToText[this.selectedOptions[2]];
      }
      this.salonCode = pinyin.getCamelChars(codeToText[this.selectedOptions[0]]).slice(0, 2);
      this.salonCode += pinyin.getCamelChars(codeToText[this.selectedOptions[1]]).slice(0, 2);
      this.salonCode += new Date().format('yyMMdd').slice(1);
    },
    handleSalonChange: async function () {
      this.salon.salonId;
      const st = this.salonList.find(x => x.id === this.salon.salonId);
      if (st) {
        this.salon.salonCode = st.code;
        this.salon.salonName = st.sname;
        this.$emit('selected', { ...this.salon });
      }
    },
    loadShowSalons: async function () {
      if (this.mode === 1) {
        return;
      }
      if (this.isSalonLoading) {
        return;
      }
      this.isSalonLoading = true;
      this.salonList.splice(0, this.salonList.length);
      const callFunc = this.isAdmin ? getSalonByRegion : getSalonInRegion;
      const params = {};
      if (this.isAdmin && this.regionCode) {
        params.regionCode = this.regionCode;
      }
      const errAlertMsg = '查询门店列表失败';
      await callFunc(params)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          if (ret && ret.length) {
            ret.forEach(x => {
              this.salonList.push({ id: '' + x.id, sname: x.sname, code: x.code });
            });
          }
          if (this.deptId == 15) {
            this.handleSalonChange();
          }
        })
        .catch(err => {
          console.error(err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => (this.isSalonLoading = false));
    },
    setRegionPath(path) {
      this.selectedOptions.splice(0, this.selectedOptions.length);
      const _cascader = this.$refs.refCascader;
      if (_cascader) {
        _cascader.$refs.panel.checkedValue = [];
        _cascader.$refs.panel.activePath = [];
        _cascader.$refs.panel.clearCheckedNodes();
      }
      if (path) {
        this.keyForCascader += 1;
      }
      if (path.length) {
        const cpyPath = []; // 必须拷贝一份，因为这份数据会随着级联选择框的刷新而回收，如果不拷贝，会影响到外部的数据
        cpyPath.push(...path);
        this.depth = cpyPath.length;
        this.handleDepthChange();
        this.selectedOptions = cpyPath; // 这里只能赋值，不能 push
        this.initRegionPath(cpyPath);
        this.loadShowSalons();
      }
    },
    setSalonId(sid, disabled) {
      if (sid) {
        this.salon.salonId = '' + sid;
        if (disabled) {
          this.isDisabled = true;
        }
      }
    },
    clearSelected() {
      this.salon.salonId = undefined;
      this.salon.salonCode = undefined;
      this.salon.salonName = undefined;
    },
    getSalonSelected() {
      const cpy = {};
      if (!this.salon.salonId) {
        return cpy;
      }
      cpy.salonId = this.salon.salonId;
      const st = this.salonList.find(x => x.id === this.salon.salonId);
      if (st) {
        cpy.salonCode = st.code;
        cpy.salonName = st.sname;
      }
      return cpy;
    },
  },
};
</script>

<style lang="scss" scoped>
.salon_region_select {
  .resion_select {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    gap: 5px;
  }
}

.srcol {
  min-width: 346px;
  display: block;
}

.srrow {
  min-width: 692px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  gap: 3px;
}

.ssalon {
  min-width: 346px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

::v-deep .resion_select .el-radio-button__inner {
  padding: 8px 8px;
}
</style>
